import { Button, List, InputItem, WhiteSpace } from 'antd-mobile-v2';
import { createForm } from '@/components/rc-form';
import React, { useState, FC } from 'react';
import { connect } from 'react-redux';
import styles from './index.module.less';
import _ from 'lodash';
import { ConnectProps } from 'typings/connect';
import { useHistory } from 'react-router-dom';

interface ILoginProps extends ConnectProps {
  // submitting?: boolean;
  form: any;
}

const isMPStrict = (value = '') => /1[0-9]{10}/g.test(value);
const isEmail = (value = '') =>
  /[0-9a-zA-Z]{1,}@[0-9a-zA-Z]{1,}\.(com|cn)/g.test(value);

const Login: FC<ILoginProps> = (props) => {
  // const { submitting } = props;
  // const [form] = Form.useForm();
  const history = useHistory();
  const { form } = props;
  // const [isPasswordLogin] = useState(true);
  // const [commonValue] = useState('');
  const [formValues, setFormValues] = useState({});

  const handleSubmit = async () => {
    const values = form.getFieldsValue();
    await form.validateFields();
    if (_.isEqual(values, formValues)) return;
    setFormValues(values);
    if (props.dispatch) {
      props
        .dispatch({
          type: 'user/getToken',
          payload: { ...values }
        })
        .then((res: any) => {
          if (res && res.status === 200) {
            history.replace('/approvalList');
          }
        });
    }
  };

  // useEffect(() => {
  //   // const key = isPasswordLogin ? 'username' : 'phone';
  //   // form.setFieldsValue({
  //   //   [key]: commonValue,
  //   // });
  // }, [commonValue, form]);

  const errors = form.getFieldError('mobile');
  const errorsPassword = form.getFieldError('password');

  return (
    <div className={styles.main}>
      <h1 className={styles.title}>用户登录</h1>
      <List style={{ margin: '5px 0', backgroundColor: '#f5f5f9' }}>
        <InputItem
          {...form.getFieldProps('mobile', {
            onChange() {
              // TODO
            }, // have to write original onChange here if you need
            rules: [
              { required: true, message: '请输入手机号' },
              {
                validator: (_a: any, value: any) =>
                  value
                    ? isEmail(value) || isMPStrict(value)
                      ? Promise.resolve()
                      : Promise.reject(new Error('邮箱/手机号格式错误'))
                    : Promise.resolve()
              }
            ]
          })}
          placeholder="邮箱/手机号"
          maxLength={50}
        >
        </InputItem>
        <span className={styles.errorMsg}>
          {errors ? errors.join(',') : null}
        </span>
        <WhiteSpace />
        <InputItem
          {...form.getFieldProps('password', {
            rules: [
              {
                required: true,
                message: '请输入密码'
              }
            ]
          })}
          placeholder="密码"
          maxLength={50}
        >
        </InputItem>
        <span className={styles.errorMsg}>
          {errorsPassword ? errors.join(',') : null}
        </span>
        <WhiteSpace />
        <Button size="large" type="primary" onClick={handleSubmit}>
          登 录
        </Button>
      </List>
    </div>
  );
};
const LoginWrap = createForm()(Login);
export default connect()(LoginWrap);
